#pragma once

#include <iostream>
#include <memory>
#include <string>
#include <cstdlib>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include "log.hpp"
#include "InetAddr.hpp"

// 套接字封装
// 模板方法模式


// 基类创建方法
const int gbacklog = 8;
const int gdefaultsockfd = -1;
namespace SocketModule
{
    enum
    {
        SOCKET_ERROR = 0,
        BIND_ERROR,
        LISTEN_ERROR
    };

    using namespace LogModule;
    class Socket;
    using SockPtr = std::shared_ptr<Socket>;

    class Socket
    {
    public:
        virtual ~Socket() = default;
        virtual void socket_or_die() = 0;
        virtual void set_socket_opt() = 0;
        virtual bool bind_or_die(int port) = 0;
        virtual bool listen_or_die() = 0;
        virtual int accepter(InetAddr *client) = 0;
        virtual void Close() = 0;
        virtual int Recv(std::string *out) = 0;
        virtual int Send(const std::string &in) = 0;
        virtual int Fd() = 0;

        void BuildTcpsocketMethood(int port)
        {
            socket_or_die();
            set_socket_opt();
            bind_or_die(port);
            listen_or_die();
        }
    };

    // 派生类实现方法

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int sockfd = -1) : _sockfd(sockfd)
        {
        }

        virtual ~TcpSocket()
        {
        }

        virtual void socket_or_die() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket error!\n");
                exit(SOCKET_ERROR);
            }
            LOG(INFO, "socket success!\n");
        }

        virtual void set_socket_opt() override
        {
            // 保证服务器在异常断开后可以立即重启
            int opt = 1;
            int n = ::setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
            (void)n;
        }

        virtual bool bind_or_die(int port) override
        {
            if (_sockfd == gdefaultsockfd)
            {
                return false;
            }

            InetAddr addr(port);
            int n = ::bind(_sockfd, addr.NetAddr(), addr.NetAddrLen());
            if (n < 0)
            {
                LOG(FATAL, "BIND_ERROR!\n");
                exit(BIND_ERROR);
            }
            LOG(INFO, "bind success!\n");
            return true;
        }

        virtual bool listen_or_die() override
        {
            if (_sockfd == gdefaultsockfd)
            {
                return false;
            }

            int n = ::listen(_sockfd, gbacklog);
            if (n < 0)
            {
                LOG(FATAL, "listen error!\n");
                exit(LISTEN_ERROR);
            }
            LOG(INFO, "listen success!\n");
            return true;
        }

        virtual int accepter(InetAddr *client) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int newsockfd = ::accept(_sockfd, (struct sockaddr *)&peer, &len);
            if (newsockfd < 0)
                return -1;
            client->SetAddr(peer, len);
            return newsockfd;
            // return std::make_shared<TcpSocket>(newsockfd);
        }

        virtual void Close() override
        {
            if (_sockfd == gdefaultsockfd)
                return;
            ::close(_sockfd);
        }

        virtual int Recv(std::string *out) override
        {
            char buffer[1024 * 8];
            int size = ::recv(_sockfd, buffer, sizeof(buffer), 0);
            if (size > 0)
            {
                buffer[size] = 0;
                *out = buffer;
            }
            return size;
        }
        virtual int Send(const std::string &in) override
        {
            int size = ::send(_sockfd, in.c_str(), in.size(), 0);
            return size;
        }

        virtual int Fd() override
        {
            return _sockfd;
        }

    private:
        int _sockfd;
    };
}